package com.pospi.xstore.ui.cash_ui;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.CountSAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.CaptureActivity;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.count.CountActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.SaveOrderInfo;
import com.pospi.xstore.view.swipemenulistview.SwipeMenu;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuCreator;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuItem;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuListView;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/*
* 采购入库
* */
public class ReceiveActivity extends BaseActivity {

    @Bind(R.id.iv_search_counts)
    ImageView iv_search_counts;
    @Bind(R.id.iv_scan_counts)
    ImageView iv_scan_counts;
    @Bind(R.id.counts_start)
    TextView counts_start;
    @Bind(R.id.parent_receive)
    LinearLayout parent;

    @Bind(R.id.lv_goods_counts)
    SwipeMenuListView lv_goods_counts;

    @Bind(R.id.et_code_counts)
    EditText et_code_counts;
    @Bind(R.id.count_date)
    TextView count_date;

    private List<GoodsDto> goodsDtos = new ArrayList<>();
    private CountSAdapter sAdapter;
    private GoodsDao dao;
    private String sid;
    private String type;
    private LoadingDialog dialog;
    private PopupWindow popupWindow;
    private int width;
    private int height;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_receive_goods);
        setTitle("录入商品");
        setMenuText("清空");
        ButterKnife.bind(this);
        dao = new GoodsDao(getApplicationContext());
        sid = getIntent().getStringExtra("billno");
        type = getIntent().getStringExtra("type");
        init();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeDialog();
                    goodsDtos.clear();
                    sAdapter.notifyDataSetChanged();
                    new AlertDialog.Builder(ReceiveActivity.this)
                            .setMessage("上传成功")
                            .setPositiveButton("返回", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    finish();
                                }
                            }).setCancelable(false)
                    .show();
                    break;
                case 2:
                    dialog.loadFailed();
                    break;
            }
        }
    };

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("是否清空数据？");
        dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                goodsDtos.clear();
                sAdapter.notifyDataSetChanged();
            }
        });
        dialog.setNeutralButton("取消", null);
        dialog.show();


    }

    @Override
    protected void onStart() {
        super.onStart();
        et_code_counts.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                search(et_code_counts.getText().toString().trim());
                return false;
            }
        });
        et_code_counts.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {


            }
        });

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        adapteData(GetData.getYYMMDDTime());

    }
    private GoodsDto gd;
    private void init() {

        sAdapter = new CountSAdapter(this, goodsDtos);
        lv_goods_counts.setAdapter(sAdapter);
        lv_goods_counts.setOnItemClickListener(new AdapterView.OnItemClickListener() {



            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                gd = goodsDtos.get(i);
                showInput();


            }
        });
        iv_search_counts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search(et_code_counts.getText().toString().trim());


            }
        });
        iv_scan_counts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //扫描
               requestCemera();
            }
        });
        counts_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //开始上传
//                testload();
                if (goodsDtos.size() == 0) {
                    return;
                }
                JSONArray array = new JSONArray();
                for (GoodsDto dto : goodsDtos) {
                    JSONObject object = new JSONObject();
                    try {
                        object.put("id", dto.getSid());
                        object.put("dhsl", dto.getNum());
                        array.put(object);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                showDialog();
                upLoad(sid, type, array.toString());

            }
        });
        setSwipeListView();
    }
    private EditText et_table;

    private void showInput() {
        View contentView = View.inflate(this, R.layout.num_item, null
        );
        final PopupWindow popupWindow = new PopupWindow(contentView, getWidth() * 2 / 3, getHeight() * 3 / 5);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        TextView sure = (TextView) contentView.findViewById(R.id.sure_table);
        TextView name_table = (TextView) contentView.findViewById(R.id.name_table);
        et_table = (EditText) contentView.findViewById(R.id.et_table);
        TextView clear_table = (TextView) contentView.findViewById(R.id.clear_table);


        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                if (et_table.getText().toString().trim().isEmpty()) {
                    return;
                }
                gd.setNum(Double.parseDouble(et_table.getText().toString().trim()));
                sAdapter.notifyDataSetChanged();

            }
        });
        clear_table.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_table.setText("");
                numberAdd = "";
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                numberAdd = "";
            }
        });
    }
    private String numberAdd = "";

    public void popupWindowNumberClick(View view) {
        TextView tv = (TextView) view;
        if (numberAdd.isEmpty()) {
            if (view.getId() != R.id.dian) {
                numberAdd += tv.getText().toString();
            }
        } else {
            if (numberAdd.equals("0") && view.getId() == R.id.dian) {
                numberAdd = tv.getText().toString();
            } else {
                numberAdd += tv.getText().toString();
            }
        }
        et_table.setText(numberAdd);
    }

    private void requestCemera() {
        if (PermissionsUtil.hasPermission(this, Manifest.permission.CAMERA)) {
            //有访问摄像头的权限
            //扫描
            Intent intent = new Intent(ReceiveActivity.this, CaptureActivity.class);
            startActivityForResult(intent, 1);
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    //用户授予了访问摄像头的权限
                    //扫描
                    Intent intent = new Intent(ReceiveActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, 1);
                }


                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    //用户拒绝了访问摄像头的申请
                }
            }, new String[]{Manifest.permission.CAMERA});
        }
    }

    private void testload() {
        showDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void setSwipeListView() {
        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xD9, 0x47,
                        0x47)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("删除");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);
            }
        };
        // set creator
        lv_goods_counts.setMenuCreator(creator);

        // step 2. listener item click event
        lv_goods_counts.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
//                GoodsDto item = goodsDtos.get(position);
//					delete(item);
                goodsDtos.remove(position);
                sAdapter.notifyDataSetChanged();
            }
        });

        // set SwipeListener
        lv_goods_counts.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    private void search(String code) {
        //搜索
        GoodsDto goodsDto = dao.selectGoods(code);
        if (goodsDto != null) {
            check(goodsDto);
        } else {
            Toast.makeText(this, "商品不存在", Toast.LENGTH_SHORT).show();
        }
        et_code_counts.setText("");
        sAdapter.notifyDataSetChanged();
        lv_goods_counts.setFocusable(false);
        ETRequestFocus();
    }
    public void ETRequestFocus() {
        et_code_counts.setFocusable(true);
        et_code_counts.setFocusableInTouchMode(true);
        et_code_counts.requestFocus();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (requestCode == 1) {
                search(data.getStringExtra("code"));
//                judgeCode(data.getStringExtra("code"));
            }
        }
    }

    private void check(GoodsDto gd) {
        for (GoodsDto dto : goodsDtos) {
            if (dto.getSid().equals(gd.getSid())) {
                dto.setNum(DoubleSave.doubleSaveTwo(dto.getNum() + 1));
                return;
            }
        }
        goodsDtos.add(gd);
    }

    public void showDialog() {
        dialog = new LoadingDialog(this);
        dialog.setLoadingText("单据上传中...")
                .setSuccessText("单据上传成功")
                .setFailedText("单据上传失败")
                .setDrawColor(Color.GRAY)
                .setLoadSpeed(LoadingDialog.Speed.SPEED_TWO)
                .show();


    }

    public void closeDialog() {
        if (dialog != null) {
            dialog.close();
            dialog = null;
        }
    }


    //上传
    private void upLoad(String id, String type, String goodsDetail) {

        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("type", type);
        params.put("goods", goodsDetail);
        Log.i("detail", params.toString());
        LoadServer.getConnect(this, Api.SYNC_RECEIVE_UP, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("up", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    if (object.getString("code").equals("1")) {
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    } else {
                        dialog.setFailedText(object.getString("msg"));
                        Message message = Message.obtain();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 2;
                handler.sendMessage(message);
            }
        });
    }
    private void showSuccss(){
        View contentView = LayoutInflater.from(this).inflate(R.layout.upload_dialog, null);
        popupWindow = new PopupWindow(contentView, 1000, 1300);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        Button button = (Button) contentView.findViewById(R.id.btn_back);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ReceiveActivity.this.finish();
            }
        });
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        popupWindow.setOutsideTouchable(false);

    }

    private int  getWidth(){
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        return dm.widthPixels;
    }
    private  int getHeight(){
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        return dm.heightPixels;
    }
}